#! /usr/bin/env python
# -*- coding: utf-8 -*-

import requests,re
import char,urllib,IO,collections

class net:
	url=''
	#响应超时时间
	timeout=0
	#模仿浏览器伪造的头信息
	header={
		'Host': '',
		'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
		'Accept-Language': 'zh-CN,en-US;q=0.5',
		'Accept-Encoding': 'utf-8',
		'Upgrade-Insecure-Requests': '1',
		'DNT': '1',
		'Referer': '',
		'Connection': 'keep-alive',
		'Cache-Control': 'max-age=0'
	}

	#初始化操作，该类传入url和响应超时时间，其中响应超时时间不是必须的
	def __init__(self,url,timeout=5):
		self.url=url
		self.header['Host']=char.GetHost(url)
		self.header['Referer']=url
		self.timeout=timeout

	#GET请求，得到页面内容对象
	def GET(self):
		url=char.ChkAccord(self.url)
		try:
			tmp=requests.get(url=url,timeout=self.timeout,headers=self.header)
			#找到编码
			charset=re.search('(?<=charset=)[^\'\"]*',tmp.text)
			if(charset==None or len(charset.group())>20):
				tmp.encoding=tmp.apparent_encoding
			else:
				tmp.encoding=charset.group()
			return tmp.text
		except:
			return None

	#DEAD请求，得到字典结构
	def HEAD(self):
		url=char.ChkAccord(self.url)
		try:
			tmp=requests.head(url=url,timeout=self.timeout,headers=self.header)
			return tmp.headers
		except:
		 	return None